<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>友情链接</span>
			<el-button v-permission="'promotion:link:create'" type="primary" plain @click="insert_dialog_visible = true"
				icon="el-icon-circle-plus-outline">
				添加链接
			</el-button>
		</div>
		<el-table :data="tableData">
			<el-table-column prop="link_id" label="#"></el-table-column>
			<el-table-column prop="title" label="链接标题"></el-table-column>
			<el-table-column prop="url" label="网站地址"></el-table-column>
			<el-table-column prop="link_order" label="排序数字"></el-table-column>
			<el-table-column label="状态">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.usable === 1" type="success">启用</el-tag>
					<el-tag v-if="scope.row.usable === -1" type="danger">禁用</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="create_time" label="添加日期"></el-table-column>
			<el-table-column label="操作" width="300">
				<!-- 复杂结构的固定写法：slot-scope="scope" -->
				<template slot-scope="scope">
					<el-button v-permission="'promotion:link:edit'" type="primary" plain icon="el-icon-edit"
						@click="openEditDialog(scope.row)">编辑
					</el-button>
					<el-button v-permission="'promotion:link:switch'" v-if="scope.row.usable === 1" type="info" plain
						icon="el-icon-lock" @click="handleBanned(scope.row.link_id, scope.$index)">禁用</el-button>
					<el-button v-permission="'promotion:link:switch'" v-if="scope.row.usable === -1" type="success" plain
						icon="el-icon-key" @click="handleOpen(scope.row.link_id, scope.$index)">启用</el-button>
					<el-button v-permission="'promotion:link:remove'" type="danger" plain icon="el-icon-delete"
						@click="handleRemove(scope.row.link_id, scope.$index)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加友情链接 -->
		<el-dialog title="添加友情链接" :visible.sync="insert_dialog_visible" @close="handleCloseDialog('insert_form')">
			<el-form :model="insert_form" ref="insert_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="链接标题:" prop="title">
					<el-input type="text" v-model="insert_form.title" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="链接地址:" prop="url">
					<el-input type="text" v-model="insert_form.url" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="显示顺序:" prop="link_order">
					<el-input type="text" v-model="insert_form.link_order" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="insert_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleInsert">添加</el-button>
			</span>
		</el-dialog>

		<!-- 编辑标签 -->
		<el-dialog title="编辑友情链接" :visible.sync="edit_dialog_visible" @close="handleCloseDialog('edit_form')">
			<el-form :model="edit_form" ref="edit_form" status-icon label-width="100px" :rules="rules">
				<el-form-item label="链接标题:" prop="title">
					<el-input type="text" v-model="edit_form.title" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="链接地址:" prop="url">
					<el-input type="text" v-model="edit_form.url" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="显示顺序:" prop="link_order">
					<el-input type="text" v-model="edit_form.link_order" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="edit_dialog_visible = false">取消</el-button>
				<el-button type="primary" @click="handleEdit">保存</el-button>
			</span>
		</el-dialog>
	</el-card>
</template>

<script>
import { Link } from '@/api';
export default {
	name: 'list',
	data() {
		return {
			insert_dialog_visible: false,
			edit_dialog_visible: false,
			tableData: [],
			insert_form: {
				title: '',
				url: 'http://',
				link_order: '',
				create_time: new Date().toLocaleString(),
			},
			edit_form: {
				title: '',
				url: '',
				link_order: '',
				link_id: '',
				create_time: new Date().toLocaleString(),
			},
			current_link: '',
			rules: {
				title: [{ required: true, message: "请填写链接名称！", trigger: 'blur' }],
				url: [
					{ required: true, message: "请填写网站地址！", trigger: 'blur' },
					{
						pattern: /^(http:\/\/|https:\/\/)?(www\.)?[a-z0-9]+\.[a-z]{2,}(\.[a-z]{2,})?$/i,
						message: '请填写合规的网址！',
						trigger: 'blur'
					}
				],
				link_order: [{ required: true, message: "填写显示顺序！", trigger: 'blur' }],
			},
		}
	},
	// 在created或mounted发送ajax请求(通过调用函数)
	created() {
		document.title = "友情链接页";
		this.loadList();
	},
	methods: {
		// 一般将发送AJAX写到methods中
		// 加载列表
		async loadList() {
			let { status, msg, data } = await Link.list({ pagesize: 10, pageindex: 1 });
			if (status) {
				this.tableData = data;
			} else {
				this.$message.error(msg);
			}
		},
		// 添加友情链接
		handleInsert() {
			// 1.表单验证
			this.$refs.insert_form.validate(async (valid) => {
				if (valid) {
					// 后台返回的data数据包含tag_id，由后台返回
					let { status, msg, data } = await Link.add({ ...this.insert_form });
					if (status) {
						// 操作 DOM -- 拷贝(单层对象-浅拷贝；多层对象-深拷贝)
						this.tableData.push({ ...this.insert_form, ...data });
						// 关闭弹窗
						this.insert_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			});
		},
		// 关闭弹窗，清除表单验证状态
		handleCloseDialog(formName) {
			// formName是变量，不能使用 ref.formName
			this.$refs[formName].resetFields();
		},
		// 打开编辑弹窗
		openEditDialog(link) {
			// 缓存当前操作的tag，为了后续的操作DOM，存的是指针地址
			this.current_link = link;
			// 还原表单数据，浅拷贝一个，让点击保存后才能生效(双向数据绑定在修改的同时内容跟着变，不符合实际需求)
			this.edit_form = { ...link };
			// 打开弹窗
			this.edit_dialog_visible = true;
		},
		// 编辑
		async handleEdit() {
			let { link_id } = this.edit_form;
			// 验证表单(方法2)
			try {
				let valid = await this.$refs.edit_form.validate();
				if (valid) {
					// 发送AJAX
					let { status, msg } = await Link.edit(link_id, { ...this.edit_form });
					if (status) {
						// 操作DOM：让vue知道我们修改了数据，后续vue会自动虚拟DOM、对比等操作，从而实现数据的更新
						Object.assign(this.current_link, this.edit_form);
						// 关闭弹窗
						this.edit_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			} catch (error) {
				console.log(error);
			}
		},
		// 禁用用户
		handleBanned(link_id, index) {
			this.$confirm('该操作将禁用该用户, 是否继续?', '提示', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Link.usable({ link_id, usable: -1 });
					if (status) {
						// 操作DOM
						this.tableData[index].usable = -1;
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info("已取消该操作!");
				});
		},
		// 启用用户
		handleOpen(link_id, index) {
			this.$confirm('该操作将启用该用户, 是否继续?', '提示', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Link.usable({ link_id, usable: 1 });
					if (status) {
						// 操作DOM
						this.tableData[index].usable = 1;
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info("已取消该操作！");
				});
		},
		// 删除
		handleRemove(link_id, index) {
			this.$confirm('该操作将删除该用户, 是否继续?', '提示', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Link.remove(link_id);
					if (status) {
						// 操作DOM
						this.tableData.splice(index, 1);
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info("已取消该操作！");
				});
		},
	},
}
</script>

<style lang="less" scoped>
.clearfix {
	display: flex;
	justify-content: space-between;
}
</style>
